package rsj.service.test;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.TableNode;
import org.springframework.stereotype.Component;
import rsj.api.product.entity.TestQueryParam;
import rsj.api.test.entity.DownloadOperLogColumn;
import rsj.api.test.entity.DownloadOperLogParam;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.List;


/**
 * 导出测试结果对账文件
 *
 * @author yuanqinglong
 * @since 2021/3/17 11:43
 */
@Component
public class DownloadOperLog implements ITestExportTemplateMethod {


    /**
     * 生成查询语句
     *
     * @param testQueryParam 参数
     * @return sql
     */
    @Override
    public String generateQueryStatement(TestQueryParam testQueryParam) {
        DownloadOperLogParam downloadOperLogParam = (DownloadOperLogParam) testQueryParam;
        return "SELECT log_orgp_id, log_reqtime,log_reqsernumber,log_prod_uid,CASE log_iscost WHEN '1' THEN '是' ELSE '否' END log_iscost, log_ip " +
                "FROM sys.oper_log WHERE log_reqsernumber = '" + downloadOperLogParam.getLogId() + "'";
    }


    /**
     * 生成导出的文件名称
     *
     * @param testQueryParam 参数
     * @return 文件名
     */
    @Override
    public String generateExportFileName(TestQueryParam testQueryParam) {
        DownloadOperLogParam downloadOperLogParam = (DownloadOperLogParam) testQueryParam;
        return downloadOperLogParam.getFileName();
    }

    /**
     * 查询出的字段缺少机构名称、产品名称将页面传递的机构名称、产品名称set到导出的文件中
     *
     * @param tableNode        列表数据
     * @param connection       数据库连接
     * @param testQueryParam 参数
     * @return 完整的excel字段
     */
    @Override
    public String processDataAccordingToTheSituation(TableNode tableNode, Connection connection, TestQueryParam testQueryParam) {
        DownloadOperLogParam downloadOperLogParam = (DownloadOperLogParam) testQueryParam;
        List<DownloadOperLogColumn> logColumns = JSON.parseArray(tableNode.toJson(), DownloadOperLogColumn.class);
        logColumns.forEach(downloadOperLogColumn -> {
            downloadOperLogColumn.setProdName(downloadOperLogParam.getProdName());
            downloadOperLogColumn.setOrgName(downloadOperLogParam.getOrgName());
        });
        return JSON.toJSONString(logColumns);
    }


    /**
     * 将生成的文件写入输出流
     *
     * @param jsonString 查询的数据
     * @param sheetName  导出的工作表名称
     * @return 写入文件的路径
     */
    @Override
    public OutputStream writeDataToTheOutputStream(String jsonString, String sheetName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        List<DownloadOperLogColumn> downloadExportEntities = JSON.parseArray(jsonString, DownloadOperLogColumn.class);
        EasyExcelFactory.write(outputStream, DownloadOperLogColumn.class).sheet().doWrite(downloadExportEntities);
        return outputStream;
    }


}
